package com.example.controller.buyer;

import com.example.base.BaseController;
import com.example.dto.CartItemDto;
import com.example.dto.SelectedItemsDto;
import com.example.dto.TradeDTO;
import com.example.dto.UpdatedItemDto;
import com.example.entity.CartInfo;
import com.example.entity.enums.UserPreferEnum;
import com.example.service.CartInfoService;
import com.example.service.impl.UserPreferService;
import com.example.util.RedisUtil;
import com.example.vo.IdHolder;
import com.example.vo.Result;
import com.example.vo.ResultCode;
import com.example.vo.buyer.CartGroupedByStoreVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 朽
 */
@RestController
@Slf4j
@RequestMapping("/buyer/cart")
public class CartController extends BaseController<CartInfoService, CartInfo> {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserPreferService userPreferService;

    @GetMapping("/getAll")
    @Operation(summary = "获取购物车内容")
    public Result<List<CartGroupedByStoreVo>> getCartInfo() {
        Long userId = IdHolder.getUserId();
        List<CartGroupedByStoreVo> cartItems = baseService.getCartItemsByUserId(userId);
        return Result.ok(cartItems);
    }

    @PostMapping("/addCart")
    @Operation(summary = "添加购物车")
    public Result<String> addCart(@RequestBody CartItemDto cartItemDto) {
        Long userId = IdHolder.getUserId();
        //记录浏览偏好
        userPreferService.recordUserScore(userId, cartItemDto.getSpuId(), UserPreferEnum.ADD_CART);
        boolean isAdd = baseService.addCart(userId, cartItemDto);
        if(isAdd){
            return Result.ok();
        }
        return Result.error("添加失败");
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除单项商品")
    public Result<String> deleteCart(@RequestParam Long skuId){
        Long userId = IdHolder.getUserId();
        boolean isDelete = baseService.deleteItemBySkuId(userId, skuId);
        if(isDelete){
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    @DeleteMapping("/delAll")
    @Operation(summary = "清空购物车")
    public Result<String> deleteAll(){
        Long userId = IdHolder.getUserId();
        boolean isDelete = baseService.deleteAllCart(userId);
        if(isDelete){
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    @DeleteMapping("/delSelectAll")
    @Operation(summary = "清空选中商品")
    public Result<String> deleteSelectedItems(@RequestBody String selectedItemsIds) throws IOException {
        Long userId = IdHolder.getUserId();
        ObjectMapper mapper = new ObjectMapper();
        SelectedItemsDto request = mapper.readValue(selectedItemsIds, SelectedItemsDto.class);
        List<Long> skuIds = request.getSelectedItemsIds();
        boolean isDelete = true;
        for (Long skuId : skuIds) {
            boolean result = baseService.deleteItemBySkuId(userId, skuId);
            if (!result) {
                isDelete = false;
                break;
            }
        }
        if (isDelete) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @PutMapping("/update")
    @Operation(summary = "根据属性修改skuId")
    public Result<String> updateCart(@RequestBody UpdatedItemDto updatedItemDto) throws IOException {
        Long userId = IdHolder.getUserId();
        boolean isUpdate = baseService.updateByItem(userId,updatedItemDto);
        if(isUpdate) {
            return Result.ok();
        }
        return Result.error("修改失败");
    }

    @PutMapping("/check")
    @Operation(summary = "根据商品选择框修改check")
    public Result<String> updateItemCheck(@RequestParam Long id, @RequestParam Integer check) {
        Long userId = IdHolder.getUserId();
        boolean isChecked = baseService.updateByItemCheck(userId,id,check);
        if(isChecked) {
            return Result.ok();
        }
        return Result.error("修改失败");
    }

    @PutMapping("/check/store")
    @Operation(summary = "根据店铺选择框修改check")
    public Result<String> updateStoreItemCheck(@RequestParam Long storeId, @RequestParam Integer check) {
        Long userId = IdHolder.getUserId();
        boolean isUpdated = baseService.updateByStoreCheck(userId, storeId, check);
        if (isUpdated) {
            return Result.ok();
        }
        return Result.error("修改失败");
    }

    @PutMapping("/check/all")
    @Operation(summary = "根据全选框修改check")
    public Result<String> updateAllItemCheck(@RequestParam Integer check) {
        Long userId = IdHolder.getUserId();
        boolean isUpdated = baseService.updateAllItemCheck(userId, check);
        if (isUpdated) {
            return Result.ok();
        }
        return Result.error("修改失败");
    }

    @PutMapping("/count")
    @Operation(summary = "修改数量")
    public Result<String> updateCount(@RequestParam Long id, @RequestParam Integer newQuantity) {
        Long userId = IdHolder.getUserId();
        boolean isUpdated = baseService.updateCount(userId, id, newQuantity);
        if (isUpdated) {
            return Result.ok();
        }
        return Result.error("修改失败");
    }

    @ApiOperation(value = "结算")
    @PostMapping("/settle")
    public Result<String> settleOrder() {
        TradeDTO trade = baseService.settleOrder();
        if (trade != null && trade.getOrders() != null && !trade.getOrders().isEmpty()) {
            // 将订单数据存储到 Redis
            String orderKey = "order:" + UUID.randomUUID().toString();
            redisUtil.set(orderKey, trade, 30*60); // 存储 30 分钟
            return Result.ok(orderKey);
        } else {
            return Result.error(ResultCode.GOOD_NOT_SELECTED);
        }
    }

//    @ApiOperation(value = "结算")
//    @PostMapping("/settle")
//    public Result<TradeDTO> settleOrder(@RequestBody CouponDiscountDTO couponDiscountDTO) {
//        TradeDTO trade = baseService.settleOrder(couponDiscountDTO);
//        System.out.println(trade);
//        return Result.ok(trade);
//    }


}

